package codeTop;

import java.util.*;

public class q207 {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<List<Integer>> grid = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            grid.add(new ArrayList<>());
        }
        int[] inDegree = new int[numCourses];
        for (int[] prerequisite : prerequisites) {
            grid.get(prerequisite[1]).add(prerequisite[0]);
            inDegree[prerequisite[0]]++;
        }
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (inDegree[i] == 0) {
                queue.add(i);
            }
        }
        int cnt = 0;
        while (!queue.isEmpty()) {
            Integer poll = queue.poll();
            cnt++;
            for (Integer i : grid.get(poll)) {
                if (--inDegree[i] == 0) {
                    queue.add(i);
                }
            }
        }
        return cnt==numCourses;
    }
}
